#include "server.h"
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
Server::Server(QWidget *parent) : QWidget(parent)
{
    m_tcpServer = new QTcpServer(this);
    m_tcpServer->listen(QHostAddress::LocalHost, 8888);
    recvTextEdit = new QTextEdit(this);
    recvTextEdit->setEnabled(false);
    statusLabel = new QLabel(tr("No connection."), this);

    sendLineEdit = new QLineEdit(this);
    sendBtn = new QPushButton(tr("Send"), this);
    sendBtn->setEnabled(false);

    QHBoxLayout* bottomLayout = new QHBoxLayout;
    bottomLayout->addWidget(statusLabel);
    bottomLayout->addStretch();
    bottomLayout->addWidget(sendBtn);

    QVBoxLayout* mainLayout= new QVBoxLayout;
    mainLayout->addWidget(recvTextEdit);
    mainLayout->addWidget(sendLineEdit);
    mainLayout->addLayout(bottomLayout);
    setLayout(mainLayout);

    connect(m_tcpServer, SIGNAL(newConnection()), this, SLOT(newConnected()));
    connect(sendBtn, SIGNAL(clicked()), this, SLOT(sendMsg()));
}

Server::~Server()
{

}

void Server::sendMsg()
{
    QString text = sendLineEdit->text();
    if (text.isEmpty())
        return;
    else
        m_tcpSocket->write(text.toStdString().c_str(),
                           strlen(text.toStdString().c_str()));
    recvTextEdit->append("Me: " + text);
    sendLineEdit->clear();
}

void Server::newConnected()
{
    m_tcpSocket = m_tcpServer->nextPendingConnection();
    statusLabel->setText(tr("connecting..."));
    statusLabel->setText("Connected.");
    sendBtn->setEnabled(true);
    connect(m_tcpSocket, SIGNAL(readyRead()), this, SLOT(readMsg()));
}

void Server::readMsg()
{
    QByteArray buffer = m_tcpSocket->readAll();
    QString text = QVariant(buffer).toString();
    recvTextEdit->append("He: " + text);
}

